package Dao.imp;

import entity.Product;
import mapper.ProductMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import utils.SqlSessionFactoryUtils;

import java.util.List;

public class ProductDao implements ProductMapper {

    private SqlSessionFactory sqlSessionFactory;

    public ProductDao() {
        sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
    }

    @Override
    public int addProduct(Product product) {
        int result = -1;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            result = session.insert("addProduct", product);
            session.commit();
        }
        return result;
    }

    @Override
    public int deleteProduct(int pid) {
        int result = -1;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            result = session.delete("deleteProduct", pid);
            session.commit();
        }
        return result;
    }

    @Override
    public int updateProduct(Product product) {
        int result = -1;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            result = session.update("updateProduct", product);
            session.commit();
        }
        return result;
    }

    @Override
    public Product queryProduct(int pid) {
        Product product = null;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            product = session.selectOne("queryProduct", pid);
        }
        return product;
    }

    @Override
    public int queryProductPid(String pname) {
        int pid = -1;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            pid = session.selectOne("queryProductPid", pname);
        } catch (NullPointerException e) {
            return -1;
        }
        return pid;
    }

    @Override
    public List<Product> queryAllProduct() {
        List<Product> list = null;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            list = session.selectList("queryAllProduct");
        }
        return list;
    }

    @Override
    public List<Product> queryProductByPname(String pname) {
        List<Product> list = null;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            list = session.selectList("queryProductByPname", pname);
        }
        return list;
    }

    @Override
    public int getProductCount() {
        int result = -1;
        try (SqlSession session = sqlSessionFactory.openSession()) {
            result = session.selectOne("getProductCount");
        }
        return result;
    }
}
